package cn.edu.tjufe.llp.tin.service.part04;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.springframework.data.jpa.domain.Specification;

import cn.edu.tjufe.llp.tin.model.bsc.BscBook;

public class BookSpecifications {
	
	public static Specification<BscBook> normalCondition(String name, String author, String publisher, LocalDate begin,
			LocalDate end) {
		return (root, query, criteriaBuilder) -> {

			List<Predicate> predicates = new ArrayList<>();
			
			predicates.add(criteriaBuilder.equal(root.<Long>get("deleted"), 0));

			if (name != null) {
				predicates.add(criteriaBuilder.like(root.<String>get("name"), "%" + name + "%"));
			}
			if (author != null) {
				predicates.add(criteriaBuilder.like(root.<String>get("author"), "%" + author + "%"));
			}
			if (publisher != null) {
				predicates.add(criteriaBuilder.like(root.<String>get("publisher"), "%" + publisher + "%"));
			}
			if (begin != null) {
				predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<LocalDate>get("pubDate"), begin));
			}
			if (end != null) {
				predicates.add(criteriaBuilder.lessThanOrEqualTo(root.<LocalDate>get("pubDate"), end));
			}

			return criteriaBuilder.and(predicates.stream().toArray(Predicate[]::new));
		};
	}

}
